package com.taikang.hmp.frame.common.chat;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Service;

/**
 * Created by reed on 2014/12/17.
 */
@Service("dBConnectionService")
public class DBCPConnectionServiceImpl implements DBConnectionService {
    /**
     * 根据配置信息取得数据库连接
     *
     * @param driverClassName
     * @param url
     * @param userName
     * @param password
     * @return
     */
    @Override
    public Connection getConnection(String driverClassName, String url, String userName, String password) {
        DataSource ds = this.getDataSource(driverClassName, url, userName, password);
        Connection conn = null;
        try {
            conn = ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 取得数据源
     * @param driverClassName
     * @param url
     * @param userName
     * @param password
     * @return
     */
    private DataSource getDataSource(String driverClassName, String url, String userName, String password){
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUsername(userName);
        ds.setPassword(password);
        ds.setUrl(url);
        return ds;
    }
}
